<?php

namespace App\Http\Controllers\Admin\User;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use Crypt;
use DB;
use Session;
use Hash;
class UsersController extends Controller
{
    //添加用户
    public function add(){
        return view('admin.users.add',['title' => '用户添加']);
    }

    //插入数据
    public function insert(Request $request){

        //表单验证以及验证错误的提示信息
        $this->validate($request, [
        'email' => 'required|email|unique:users',
        'password' => 'required|min:6|max:18',
        'repassword' => 'required|same:password'
        ],[
            'email.required' => '邮箱不能为空',
            'email.email' => '邮箱格式不对',
            'email.unique' => '此邮箱已被注册',
            'password.required' => '密码不能为空',
            'password.min' => '密码不能少于6位',
            'password.max' => '密码不能大于18位',
            'repassword.required' => '确认密码不能为空',
            'repassword.same' => '确认密码不一致'
        ]);

        //取出不需要的字段
        $data = $request -> except('_token','repassword');

        //处理密码
        $data['password'] = Crypt::encrypt($data['password']);

        //处理token字段
        $data['remember_token'] = str_random(50);

        //获取时间戳
        $time = time();

        //把注册时间放入数组
        $data['regtime'] = $time;

        //处理头像
        //判断文件是否上传
        if($request -> hasfile('pic'))
        {
            //判断文件是否有效
            if($request -> file('pic') ->isvalid())
            {
                //获取图片后缀名
                $suffix = $request -> file('pic') -> getClientOriginalExtension();

                //为图片准备随机不重复的名称
                $fileName = $time.mt_rand(10000,99999). '.' .$suffix;

                //移动文件
                $move = $request -> file('pic') -> move('./uploads/portrait', $fileName);

                //判断是否移动成功
                if($move)
                {
                    //成功,改变pic的值,以便存入数据库
                    $data['pic'] = $fileName;

                }
            }
        }
        //把数据写入数据库
        $id = DB::table('users') -> insertGetId($data);

        if($id)
        {
            //成功,跳转到用户列表
            $res = DB::table('users_detail') -> insert(['uid' => $id, 'nickname' => $data['email']]);
            if($res)
            {
                $res = DB::table('address') -> insert(['uid' => $id]);
                if($res)
                {
                    return redirect('/admin/user/list') -> with(['info' => '添加成功']);
                }else
                {
                    DB::rollBack();
                    return back();
                }
                
            }else
            {
                DB::rollBack();
                return back();
            }
        }else
        {
            //失败跳回
            DB::rollBack();
            return back();
        }
    }

    //用户列表
    public function userlist(Request $request)
    {

        //取出数据库中数据
        $data = DB::table('users')-> where('email','like', '%'.$request -> input('keywords').'%') -> where('admin_user', '=', '0') -> paginate(10);

        return view('admin.users.list', ['data' => $data, 'request' => $request -> all(), 'title' => '用户列表']);
    }

    //修改用户状态
    public function alterStatus(Request $request)
    {
        $id = $request -> input('id');
        //查询
        $status = DB::table('users') -> where('id', $id) -> first() -> status;

        //更改数据库
        if($status == 0)
        {
            $res = DB::table('users') -> where('id', $id) -> update(['status' => 1]);
            if($res)
            {
                return 1;
            }else
            {
                return 2;
            }
        }elseif($status == 1)
        {
            $res = DB::table('users') -> where('id', $id) -> update(['status' => 0]);
            if($res)
            {
                return 0;
            }else
            {
                return 2;
            }
        }
    }

    //删除用户
    public function delete($id)
    {
        //取出头像文件名称
        $data = DB::table('users') -> where('id', $id) -> first();

        $pic = $data -> pic;

        //删除收货地址
        $res = DB::table('address') -> where('uid', $id);
        if(!$res)
        {
            return back() -> with('info', '删除失败');
        }

        //从数据库删除用户
        $res = DB::table('users') -> delete($id);

        //判断结果
        if($res)
        {
            //判断文件是否存在
            if(file_exists('./uploads/portrait/'.$pic))
            {
                //判断文件是否是默认头像
                if($pic != 'default.jpg')
                {
                    //删除头像文件
                    $del = unlink('./uploads/portrait/'.$pic);
                    if($del)
                    {
                        return redirect('/admin/user/list') -> with(['info' => '删除成功']);
                    }
                }else
                {
                    return redirect('/admin/user/list') -> with(['info' => '删除成功']);
                }
            }else
            {
                return redirect('/admin/user/list') -> with(['info' => '数据已删除,头像文件未找到']);
            }

        }else
        {
            return back() -> with(['info' => '删除失败']);
        }

    }

    //显示用户详情
    public function detail($id)
    {
        $user = DB::table('users') -> where('id',$id) -> first();
        $detail = DB::table('users_detail') -> where('uid', $id) -> first();
        $address = DB::table('address') -> where('uid', $id) -> get();
        return view('admin.users.detail', ['user' => $user, 'detail' => $detail ,'address' => $address ,'title' => '管理员列表']);
    }

    //管理员详情
    public function admindetail($id)
    {
        $data = DB::table('users') -> where('id',$id) -> first();
        return view('admin.users.admindetail', ['data' => $data,'title' => '管理员列表']);
    }

    //管理员列表
    public function adminlist(Request $request)
    {

        //取出数据库中数据
        $data = DB::table('users')-> where('email','like', '%'.$request -> input('keywords').'%') -> where('admin_user', '=', '1') -> paginate(10);

        return view('admin.users.adminlist', ['data' => $data, 'request' => $request -> all(),'title' => '管理员列表']);
    }

    //编辑管理员
    public function edit($id)
    {
        $data = DB::table('users') -> where('id',$id) -> first();
        return view('admin.users.edit',['data' => $data, 'title' => '管理员编辑']);
    }

    //编辑管理员
    public function doedit(Request $request)
    {   
        //表单验证以及验证错误的提示信息
        $this->validate($request, [
        'password' => 'required|min:6|max:18',
        'repassword' => 'required|same:password'
        ],[
            'password.required' => '密码不能为空',
            'password.min' => '密码不能少于6位',
            'password.max' => '密码不能大于18位',
            'repassword.required' => '确认密码不能为空',
            'repassword.same' => '确认密码不一致'
        ]);
        //取出不需要的字段
        $data = $request -> except('_token','repassword');
        
        //处理密码
        $data['password'] = Crypt::encrypt($data['password']);

        //处理token字段
        $data['remember_token'] = str_random(50);

        //获取时间戳
        $time = time();

        //获取旧的头像信息
        $res =  DB::table('users') -> select('pic') -> where('id', $data['id']) ->first();

        $oldpic = $res -> pic;
        
        
        
        // dd($data);
        //把信息写入数据库
        $res = DB::table('users') -> where('id', $data['id']) -> update(['password' => $data['password'], 'remember_token' => $data['remember_token'], 'admin_user' => $data['admin_user']]);
        if(!$res)
        {
            //失败,数据库回滚并跳转回编辑页面
            DB::rollBack();
            return redirect('/admin/user/edit') -> with(['info' => '数据修改失败', 'id' => $data['id']]);
        }

        //处理头像
        //判断文件是否上传
        if($request -> hasfile('pic'))
        {
            //判断文件是否有效
            if($request -> file('pic') ->isvalid())
            {
                //获取图片后缀名
                $suffix = $request -> file('pic') -> getClientOriginalExtension();

                //为图片准备随机不重复的名称
                $fileName = $time.mt_rand(10000,99999). '.' .$suffix;

                //移动文件
                $move = $request -> file('pic') -> move('./uploads/portrait', $fileName);

                //判断是否移动成功
                if($move)
                {
                    //成功,改变pic的值,以便存入数据库
                    $data['newpic'] = $fileName;

                }


            }
        }
        //把数据写入数据库
        $res = DB::table('users') -> where('id', $data['id']) -> update(['pic' => $data['newpic']] );

        if($res)
        {

            //判断文件是否存在
            if(file_exists('./uploads/portrait/'.$oldpic))
            {
                //判断文件是否是默认头像
                if($oldpic != 'default.jpg')
                {
                    //删除头像文件
                    $del = unlink('./uploads/portrait/'.$oldpic);
                    if($del)
                    {
                        return redirect('/admin/user/adminlist') -> with(['info' => '修改成功']);
                    }
                }else
                {
                    return redirect('/admin/user/adminlist') -> with(['info' => '修改成功']);
                }
            }else
            {
                return redirect('/admin/user/adminlist') -> with(['info' => '数据已删除,头像文件未找到']);
            }
            //成功,跳转到用户列表
            return redirect('/admin/user/adminlist');
        }else
        {
            //失败跳回
            return back();
        }
    }


    //删除管理员
    public function deleteadmin($id)
    {
        //取出头像文件名称
        $data = DB::table('users') -> where('id', $id) -> first();

        $pic = $data -> pic;


        //从数据库删除用户
        $res = DB::table('users') -> delete($id);

        //判断结果
        if($res)
        {
            //判断文件是否存在
            if(file_exists('./uploads/portrait/'.$pic))
            {
                //判断文件是否是默认头像
                if($pic != 'default.jpg')
                {
                    //删除头像文件
                    $del = unlink('./uploads/portrait/'.$pic);
                    if($del)
                    {
                        return redirect('/admin/user/adminlist') -> with(['info' => '删除成功']);
                    }
                }else
                {
                    return redirect('/admin/user/adminlist') -> with(['info' => '删除成功']);
                }
            }else
            {
                return redirect('/admin/user/adminlist') -> with(['info' => '数据已删除,头像文件未找到']);
            }

        }else
        {
            return back() -> with(['info' => '删除失败']);
        }
    }

    //用户注销
    public function quit()
    {
        session()->forget('master_admin');
        return redirect('/admin/login');
    }
    
}
